#import "FlutterJlBluetoothPlugin.h"
#import "JLFlutterBluetoothPluginNotificationConst.h"

#import <JL_BLEKit/JL_BLEKit.h>
#import <DFUnits/DFUnits.h>

#import "BLEManager.h"

#import "JLJsonTool.h"
#import "JL_EntityToJsonTool.h"

#import "JLFlutterPluginDeviceManager.h"
#import "JLFlutterPluginOtaManager.h"


@interface FlutterJlBluetoothPlugin() <FlutterStreamHandler>
@property (strong, nonatomic) FlutterEventSink  eventSink;
@property (strong, nonatomic) NSString          *otaFileDocPath;     // ota文件夹名字

@property (strong, nonatomic) BLEManager        *mBLEManager;

@end

@implementation FlutterJlBluetoothPlugin

+ (instancetype)sharedInstance {
    static FlutterJlBluetoothPlugin *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
        instance.otaFileDocPath = @"upgrade";
    });
    return instance;
}

+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"flutter_jl_bluetooth_plugin" binaryMessenger:[registrar messenger]];
    
    FlutterJlBluetoothPlugin *instance = [FlutterJlBluetoothPlugin sharedInstance];
    [registrar addMethodCallDelegate:instance channel:channel];
    
    FlutterEventChannel *eventChannel = [FlutterEventChannel eventChannelWithName:@"flutter_jl_bluetooth_plugin_event" binaryMessenger:[registrar messenger]];
    [eventChannel setStreamHandler:instance];
    
    instance.mBLEManager = [[BLEManager alloc] init];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    
    if ([JLPHONEBLUETOOTHISNOTENABLED isEqualToString:call.method]) {
        // 查询手机是否开启蓝牙
        if (self.mBLEManager.mBleManagerState != CBManagerStatePoweredOn) {
            result([NSNumber numberWithBool:NO]);
            return;
        } else {
            result([NSNumber numberWithBool:YES]);
        }
    } else if ([JLBLEGETDEVICECONNECTED isEqualToString:call.method]) {
        // 获取蓝牙设备是否连接
        if (self.mBLEManager.mBlePeripheral != nil) {
            result([NSNumber numberWithBool:YES]);
        }else{
            result([NSNumber numberWithBool:NO]);
        }
    } else if ([JLBLESTARTSCANDEVICE isEqualToString:call.method]) {
        // 搜索蓝牙设备
        [self.mBLEManager startScanBLE];
        [JL_Tools delay:2.0 Task:^{
            NSLog(@"--->已刷完.");
            [self.mBLEManager stopScanBLE];
//            [self.subTableview headerEndRefreshing];
        }];
        result([NSNumber numberWithBool:YES]);

    } else if ([JLBLESETFILTER isEqualToString:call.method]) {
        // 设置蓝牙过滤
        NSNumber *enable = call.arguments[@"enable"];
        if (enable.boolValue) {
//            txt = @"APP会过滤部分不吻合的BLE外设。";
            self.mBLEManager.isFilter  = YES;
        } else {
//            txt = @"APP会扫描所有BLE外设。";
            self.mBLEManager.isFilter = NO;
        }
        result([NSNumber numberWithBool:YES]);

    } else if ([JLBLEGETFILTER isEqualToString:call.method]) {
        // 获取蓝牙过滤
        result([NSNumber numberWithBool:self.mBLEManager.isFilter]);

    } else if ([JLBLEDEVICEREQUIRECONNECT isEqualToString:call.method]) {

        // 先断开之前的连接
        [self.mBLEManager disconnectBLE];

        // 开始连接设备
        if ([JLFlutterPluginDeviceManager sharedInstance].btEnityList == nil || [JLFlutterPluginDeviceManager sharedInstance].btEnityList.count < 1) {
            result([NSNumber numberWithBool:NO]);
            return;
        }
        NSString *identifier = call.arguments[@"identifier"];
        NSNumber *ble_pair_enable = call.arguments[@"ble_pair_enable"]; //是否通过认证方式连接设备

        self.mBLEManager.isPaired = [ble_pair_enable boolValue];
        
        for (DeviceEntity *entity in [JLFlutterPluginDeviceManager sharedInstance].btEnityList) {
            if ([entity.mPeripheral.identifier.UUIDString isEqualToString:identifier]) {
                [self.mBLEManager connectBLE:entity.mPeripheral];
                break;
            }
        }
        result([NSNumber numberWithBool:YES]);

    } else if ([JLBLEDEVICEREQUIREDISCONNECT isEqualToString:call.method]) {
        // 请求断开当前设备
        [self.mBLEManager disconnectBLE];

        result([NSNumber numberWithBool:YES]);

    } else if ([JLOTAGETFILELIST isEqualToString:call.method]) {
        // 获取ota文件夹数组
        NSString *fileDocPath = call.arguments[@"OTAFileDocPath"];
        if ((fileDocPath != nil) && (fileDocPath.length > 0)) {
            self.otaFileDocPath = fileDocPath;
        }
        [JLFlutterPluginOtaManager sharedInstance].otaUpgradeFileDocPath = self.otaFileDocPath;
        if ([JLFlutterPluginOtaManager sharedInstance].otaFileArray != nil) {
            result([JLFlutterPluginOtaManager sharedInstance].otaFileArray);
        } else {
            result([NSArray array]);
        }

    } else if ([JLOTASETSELECTFILEPATH isEqualToString:call.method]) {
        // 设置ota升级文件路径
        [JLFlutterPluginOtaManager sharedInstance].selectOtaFilePath = [DFFile listPath:NSDocumentDirectory MiddlePath:self.otaFileDocPath File:call.arguments[@"selectOTAFilePath"]];
        result([NSNumber numberWithBool:YES]);

    } else if ([JLOTAGETBLEDEVICEINFOANDSTARTOTAUPGRADE isEqualToString:call.method]) {
        // 获取设备信息，并进行OTA升级
        [[JLFlutterPluginOtaManager sharedInstance] getBleDeviceInfoWithStartOtaUpgrade:YES];
        result([NSNumber numberWithBool:YES]);

    } else if ([JLOTAGETSELECTFILEPATH isEqualToString:call.method]) {
        // 获取ota升级文件路径
        result([JLFlutterPluginOtaManager sharedInstance].selectOtaFilePath);

    } else {
        result(FlutterMethodNotImplemented);
    }
}



#pragma mark - FlutterStreamHandler

- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments eventSink:(FlutterEventSink)eventSink {
    self.eventSink = eventSink;
    // 初始化业务控制器
    [JLFlutterPluginDeviceManager sharedInstance].eventSink = eventSink;
    [JLFlutterPluginDeviceManager sharedInstance].mBLEManager = self.mBLEManager;
    
    [JLFlutterPluginOtaManager sharedInstance].eventSink = eventSink;
    [JLFlutterPluginOtaManager sharedInstance].mBLEManager = self.mBLEManager;
    return nil;
}
 
- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments {
    self.eventSink = nil;
    [JLFlutterPluginDeviceManager sharedInstance].eventSink = nil;
    [JLFlutterPluginOtaManager sharedInstance].eventSink = nil;
    return nil;
}

@end

